import { ForwardRefRenderFunction, useEffect, memo, useImperativeHandle, forwardRef, useState } from 'react'
import './style.less'
import { EMPTYTEXT, message } from '@hs-admin/utils'
import { useSearchParams } from 'react-router-dom'
import { useImmer } from 'use-immer'
import { HsAdminInput, HsAdminSpin, HsAdminSortTable } from '@hs-admin/base-components'
import { Space, Button, Switch, Tooltip, Flex } from 'antd'
import { useTypeStore } from '@/store/useBasicDataItem'
import { sortDataItemColumn, reqDataItemColumns, updateCoreFieldData } from '@/api/assetMaintain/basic/item'
import Setting from './Setting'
import { QuestionCircleOutlined } from '@ant-design/icons'

interface Props {
  back: () => void
  nextStep?: () => void
}

const Step2: ForwardRefRenderFunction<unknown, Props> = (props: Props, ref: any) => {
  const { back } = props
  const [searchParams] = useSearchParams()
  const tabKey = useTypeStore((state) => state.tabKey)
  const setTabKey = useTypeStore((state) => state.setTabKey)
  let id: string | null = searchParams.get('id') || null
  const data_item_id = useTypeStore((state) => state.data_item_id)
  if (!id && data_item_id) {
    id = data_item_id
  }

  const [isSave, setisSave] = useImmer(false)
  const [data, setData] = useImmer<any[]>([])

  const columns = [
    {
      title: '字段名',
      dataIndex: 'name'
    },
    {
      title: '中文名',
      dataIndex: 'comment'
    },
    {
      title: '字段说明',
      dataIndex: 'description',
      render: (_: any, record: any, index: number) => (
        <HsAdminInput
          defaultValue={record.description}
          maxLength="500"
          onPressEnter={(e: { target: { value: string } }) => descriptionChange('description', e.target.value, index)}
          onBlur={(e: { target: { value: string } }) => descriptionChange('description', e.target.value, index)}
          placeholder="请输入字段说明"
        />
      )
    },
    {
      title: '是否核心',
      dataIndex: 'is_core_field',
      render: (_: any, record: any) => {
        const coreType = new Map([
          [false, '否'],
          [true, '是'],
          [null, EMPTYTEXT]
        ])
        const name = coreType.get(record.is_core_field)
        return <span>{name}</span>
      }
    },
    {
      title: '安全等级',
      dataIndex: 'security_level'
    },
    {
      title: () => (
        <Flex gap={'small'}>
          <p>可搜索</p>
          <Tooltip title="在数据项查询中，该字段是否作为搜索功能中的搜索范围">
            <QuestionCircleOutlined />
          </Tooltip>
        </Flex>
      ),
      dataIndex: 'searchable',
      render: (_: any, record: any, index: number) => (
        <Switch checked={!!record.searchable} onChange={(checked) => switchChange('searchable', checked, index)} />
      )
    },
    {
      title: () => (
        <Flex gap={'small'}>
          <p>可查询</p>
          <Tooltip title="在数据项查询中，该字段是否可呈现在查询结果列表中展示">
            <QuestionCircleOutlined />
          </Tooltip>
        </Flex>
      ),
      dataIndex: 'queryable',
      render: (_: any, record: any, index: number) => (
        <Switch checked={!!record.queryable} onChange={(checked) => switchChange('queryable', checked, index)} />
      )
    },
    {
      title: () => (
        <Flex gap={'small'}>
          <p>可提供</p>
          <Tooltip title="在数据内容提供时（导出、接口、任务传输等形式），该字段是否可对外提供">
            <QuestionCircleOutlined />
          </Tooltip>
        </Flex>
      ),
      dataIndex: 'available',
      render: (_: any, record: any, index: number) => (
        <Switch checked={!!record.available} onChange={(checked) => switchChange('available', checked, index)} />
      )
    },
    {
      title: () => (
        <Flex gap={'small'}>
          <p>业务唯一</p>
          <Tooltip title="具有唯一性，可以作为数据的标识，如ID、企业名称等">
            <QuestionCircleOutlined />
          </Tooltip>
        </Flex>
      ),
      dataIndex: 'unique',
      render: (_: any, record: any, index: number) => (
        <Switch checked={record.unique} onChange={(checked) => switchChange('unique', checked, index)} />
      )
    }
  ]
  const [loading, setloading] = useState(true)

  const descriptionChange = (key: string, value: string, index: number) => {
    const item = data[index]
    item[key] = value?.trim()
    updateCoreFieldData({
      data_product_item_id: id,
      column_id: item.id,
      ...item
    }).then(() => {
      message.success('保存成功')
      callList()
    })
  }
  const switchChange = (key: string, checked: boolean, index: number) => {
    const item = data[index]
    if (key === 'searchable') {
      const hasActive = data.filter((item: { searchable: number }) => item.searchable === 1)
      if (checked) {
        if (hasActive.length >= 5) {
          message.warning('可搜索最多选择5个')
          return
        }
      } else {
        if (hasActive.length === 1) {
          message.warning('可搜索至少选择1个')
          return
        }
      }
    }
    if (key === 'queryable') {
      const hasActive = data.filter((item: { queryable: number }) => item.queryable === 1)
      if (!checked) {
        if (hasActive.length === 1) {
          message.warning('可查询至少选择1个')
          return
        }
      }
    }
    if (key === 'unique') {
      item[key] = checked
      item.available = checked ? 1 : item.available
    } else {
      item[key] = checked ? 1 : 0
    }
    if (key === 'searchable' && checked) {
      item.queryable = item.searchable
      item.available = item.searchable
    }
    if (key === 'queryable' && checked) {
      item.available = item.queryable
    }
    updateCoreFieldData({
      data_product_item_id: id,
      column_id: item.id,
      ...item
    })
      .then(() => {
        message.success('保存成功')
        callList()
      })
      .catch((error) => {
        callList()
        return Promise.reject(error)
      })
  }
  const goStep1 = () => {
    setTabKey('1')
  }
  const goStep3 = async () => {
    const isAllSearch = data.some((item: any) => item.searchable === 1)
    if (!isAllSearch) {
      message.warning('至少选择一个可搜索字段')
      return
    }
    if (!id && !isSave) {
      setTabKey('3')
      setisSave(true)
    } else {
      setTabKey('3')
    }
  }

  const callList = async () => {
    setloading(true)
    const params = {
      id
    }
    const res = await reqDataItemColumns(params)
    if (res.length) {
      setData(res)
    }
    setloading(false)
  }

  const cancel = async () => {
    setData([])
  }
  const onDragEnd = (list: any[]) => {
    list.forEach((item, index) => {
      item.position = ++index
    })
    sortDataItemColumn({
      id,
      items: list
    }).then(() => {
      callList()
    })
  }

  useEffect(() => {
    if (tabKey === '2') {
      callList()
    }
  }, [tabKey])

  useImperativeHandle(
    ref,
    () => {
      return {
        cancel
      }
    },
    []
  )

  return (
    <>
      {loading && <HsAdminSpin />}
      <HsAdminSortTable columns={columns} rowKey="id" dataSource={data} size="small" onUpdateDragEnd={onDragEnd} />
      <br />
      <Setting tableData={data} id={id} />
      <Space className="flex justify-end">
        <Button type="primary" onClick={goStep1}>
          上一步
        </Button>
        {id && <Button onClick={back}>取消</Button>}
        <Button type="primary" onClick={goStep3}>
          下一步
        </Button>
      </Space>
    </>
  )
}

export default memo(forwardRef(Step2))
